package com.friend.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.friend.util.QuestionConverter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.core.constants.Constants;
import com.common.core.domain.TableDataInfo;
import com.common.core.enums.ResultCode;
import com.common.security.exception.ServiceException;
import com.friend.domain.question.Question;
import com.friend.domain.question.dto.QuestionQueryDTO;
import com.friend.domain.question.es.QuestionES;
import com.friend.domain.question.vo.QuestionDetailVO;
import com.friend.domain.question.vo.QuestionVO;
import com.friend.integration.elasticsearch.QuestionRepository;
import com.friend.manager.QuestionCacheManager;
import com.friend.mapper.question.QuestionMapper;
import com.friend.mapper.user.UserSubmitMapper;
import com.friend.service.question.IQuestionService;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class QuestionServiceImpl implements IQuestionService {

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Override
    public TableDataInfo list(QuestionQueryDTO questionQueryDTO) {
        long count = questionRepository.count();
        if (count <= 0) {
            refreshQuestion();
        }
        Sort sort = Sort.by(Sort.Direction.ASC, "questionId");
        Pageable pageable = PageRequest.of(questionQueryDTO.getPageNum() - 1, questionQueryDTO.getPageSize(), sort);
        Integer difficulty = questionQueryDTO.getDifficulty();
        String keyword = questionQueryDTO.getKeyword();
        Page<QuestionES> questionESPage;
        if (difficulty == null && StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findAll(pageable);
        } else if (StrUtil.isEmpty(keyword)) {
            questionESPage = questionRepository.findQuestionByDifficulty(difficulty, pageable);
        } else if (difficulty == null) {
            questionESPage = questionRepository.findByTitleOrContent(keyword, keyword, pageable);
        } else {
            questionESPage = questionRepository.findByTitleOrContentAndDifficulty(keyword, keyword, difficulty, pageable);
        }
        long total = questionESPage.getTotalElements();
        if (total <= 0) {
            return TableDataInfo.empty();
        }
        List<QuestionES> questionESList = questionESPage.getContent();
        List<QuestionVO> questionVOList = BeanUtil.copyToList(questionESList, QuestionVO.class);
        return TableDataInfo.success(questionVOList, total);
    }

    @Override
    public List<QuestionVO> hotList() {
        Long total = questionCacheManager.getHostListSize();
        List<Long> hotQuestionIdList;
        if (total == null || total <= 0) {
            PageHelper.startPage(Constants.HOST_QUESTION_LIST_START, Constants.HOST_QUESTION_LIST_END);
            hotQuestionIdList = userSubmitMapper.selectHostQuestionList();
            questionCacheManager.refreshHotQuestionList(hotQuestionIdList);
        } else {
            hotQuestionIdList = questionCacheManager.getHostList();
        }
        return assembleQuestionVOList(hotQuestionIdList);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        QuestionES questionES = questionRepository.findById(questionId).orElse(null);
        QuestionDetailVO questionDetailVO = new QuestionDetailVO();
        if (questionES != null) {
            BeanUtil.copyProperties(questionES, questionDetailVO);
            return questionDetailVO;
        }
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            return null;
        }
        refreshQuestion();
        BeanUtil.copyProperties(question, questionDetailVO);
        return questionDetailVO;
    }

    @Override
    public QuestionDetailVO detail(Long questionId, Boolean forceRefresh) {
        if (forceRefresh != null && forceRefresh) {
            // 强制刷新：直接从数据库获取最新数据并同步到ES
            Question question = questionMapper.selectById(questionId);
            if (question == null) {
                return null;
            }
            try {
                // 同步到ES
                QuestionES questionES = QuestionConverter.toQuestionES(question);
                questionRepository.save(questionES);
            } catch (Exception e) {
                log.error("强制刷新ES同步失败: questionId={}", questionId, e);
            }
            // 返回详情
            QuestionDetailVO questionDetailVO = new QuestionDetailVO();
            BeanUtil.copyProperties(question, questionDetailVO);
            return questionDetailVO;
        } else {
            // 非强制刷新：使用普通detail方法
            return detail(questionId);
        }
    }


    @Override
    public String preQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        
        try {
            return questionCacheManager.preQuestion(questionId).toString();
        } catch (ServiceException e) {
            if (ResultCode.FAILED_QUESTION_NOT_IN_LIST == e.getResultCode()) {
                // 题目不在列表中，尝试刷新缓存后重试
                log.warn("题目不在缓存列表中，尝试刷新缓存: questionId={}", questionId);
                questionCacheManager.refreshCache();
                return questionCacheManager.preQuestion(questionId).toString();
            }
            throw e;
        }
    }

    @Override
    public String nextQuestion(Long questionId) {
        Long listSize = questionCacheManager.getListSize();
        if (listSize == null || listSize <= 0) {
            questionCacheManager.refreshCache();
        }
        
        try {
            return questionCacheManager.nextQuestion(questionId).toString();
        } catch (ServiceException e) {
            if (ResultCode.FAILED_QUESTION_NOT_IN_LIST == e.getResultCode()) {
                // 题目不在列表中，尝试刷新缓存后重试
                log.warn("题目不在缓存列表中，尝试刷新缓存: questionId={}", questionId);
                questionCacheManager.refreshCache();
                return questionCacheManager.nextQuestion(questionId).toString();
            }
            throw e;
        }
    }

    public void refreshQuestion() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>());
        if (CollectionUtil.isEmpty(questionList)) {
            return;
        }
        // 刷新ES索引 - 使用专门的转换工具
        List<QuestionES> questionESList = QuestionConverter.toQuestionESList(questionList);
        questionRepository.saveAll(questionESList);
        
        // 刷新Redis缓存
        questionCacheManager.refreshCache();
    }

    private List<QuestionVO> assembleQuestionVOList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return new ArrayList<>();
        }
        List<QuestionVO> resultList = new ArrayList<>();
        for (Long questionId : hotQuestionIdList) {
            QuestionDetailVO detail = detail(questionId);
            // 跳过不存在的题目
            if (detail == null) {
                continue;
            }
            QuestionVO questionVO = new QuestionVO();
            questionVO.setTitle(detail.getTitle());
            resultList.add(questionVO);
        }
        return resultList;
    }
}
